let querystring = require('querystring');
let fileUtil = require('./fileutil');
let config = require('../config');
let path = require('path');

/**
 * 自定义路由实现方式
 * @param pathname
 * @param req
 * @param res
 */
function route(pathname, req, res) {
    let method = req.method.toLowerCase();
    console.log(`Route path:${pathname}, Method:${method}`);

    switch (method) {
        case 'get':
            get(pathname, req, res);
            break;
        case 'post':
            post(pathname, req, res);
            break;
    }
}

function post(pathname, req, res) {
    res.setHeader('Content-Type', 'text/plain; charset=utf-8');
    if (pathname === '/add') {//首页
        let data = '';
        //必须要有on('data'),on('end')才会执行
        // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
        req.on('data', function (fag) {
            data += fag;
        });
        // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
        req.on('end', function () {
            // data = querystring.parse(data);
            data = JSON.parse(data);
            console.log(data);
            if (!data.fileName || data.fileName === '') {
                res.write(`文件名称不能为空！\n`);
                res.end();
            } else if (!data.fileContent || data.fileContent === '') {
                res.write(`文件内容不能为空！`);
                res.end();
            } else {
                fileUtil.writeFile(path.normalize(`${config.views}/archives/${data.fileName}`), data.fileContent, function () {
                    res.write(`文件写入成功！`);
                    res.end();
                });
            }
        });
    }
}

function get(pathname, req, res) {

    if (pathname === '/') {//首页
        let html = `<button onclick="window.location.href='/add.html'">添加页面</button><br/>`;
        fileUtil.readDir(path.normalize(`${config.views}/archives`), function (error, files) {
            if (error) {
                console.trace(error);
                return;
            }
            files.forEach(function (file) {
                html += `<a href="/archives/${file}">${file}</a><br/>`;
            });
            sendData(200, req, res, {'Content-type': 'text/html; charset=utf-8'}, html);
        });
    } else if (/^(\/)(.)*(\.html)$/.test(pathname)) {
        // let body = querystring.parse(data);
        fileUtil.readFile(`${config.views}/${pathname.substring(1, pathname.length)}`, function (error, content) {
            sendData(200, req, res, {'Content-type': 'text/html; charset=utf-8'}, content);
        });
    } else {//404
        sendData(404, req, res, null);
    }
}

/***
 * 发送数据
 * @param status
 * @param req
 * @param res
 * @param head
 * @param content
 */
function sendData(status, req, res, head, content) {
    let data = '';
    //必须要有on('data'),on('end')才会执行
    req.on('data', function (fag) {
        data += fag;
    });
    req.on('end', function () {
        if (status !== 200) {
            res.writeHead(status, head);
        } else {
            res.writeHead(200, head);
            res.write(content);
        }
        res.end();
    });
}
exports.route = route;